package top.timestreet.xmsk.qu.processor;

import org.springframework.stereotype.Service;
import top.timestreet.xmsk.base.pojo.ChapterPage;
import top.timestreet.xmsk.base.processor.BaseSite;
import top.timestreet.xmsk.util.ChapterMeta;
import top.timestreet.xmsk.util.ChapterNameUtil;
import top.timestreet.xmsk.util.DESUtil;
import top.timestreet.xmsk.util.URLConvertUtil;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.processor.PageProcessor;
import us.codecraft.webmagic.selector.Html;

/**
 * @author TateLiao
 * @data 2019年6月4日 笔趣阁（https://www.qu.la/） egPage:
 * https://www.qu.la/book/101104/5298634.html
 */
@Service
public class QuChapterPageProcessor extends BaseSite implements PageProcessor {

    @Override
    public void process(Page page) {
        Html html = page.getHtml();
        // 章节目录
        String baseUrl = getListPageUrl(page.getUrl().toString());
        ChapterPage chapterPage = new ChapterPage();
        String title = html.$("title", "text").toString();
        // 判断是否标题是否包含中文数字
        if (ChapterNameUtil.hasDigit(title) && ChapterNameUtil.chapterNameIsContriner(title)) {
            title = ChapterNameUtil.chapterNameFormat(title);
        }
        // 去除_笔趣阁
        chapterPage.setTitle(ChapterMeta.formatChapterTitle(title));
        chapterPage.setContent(ChapterMeta.formaChapterContent(html.$("#content").toString()));
        //chapterPage.setContent(html.$("#content").toString());
        // 是否为第一章
        String prevUrl = baseUrl + html.$("#pager_prev", "href").toString();
        if (ChapterMeta.isFirstOrLastChapter(prevUrl)) {
            chapterPage.setPrevUrl(URLConvertUtil.uRLConvert(DESUtil.encrypt(prevUrl)));
        }
        // 是否为最后一章
        String nextUrl = baseUrl + html.$("#pager_next", "href").toString();
        if (ChapterMeta.isFirstOrLastChapter(nextUrl)) {
            chapterPage.setNextUrl(URLConvertUtil.uRLConvert(DESUtil.encrypt(nextUrl)));
        }
        chapterPage.setListPageUrl(URLConvertUtil.uRLConvert(DESUtil.encrypt(baseUrl)));
        page.putField("chapterPage", chapterPage);
    }

    @Override
    public Site getSite() {
        return site;
    }

    private String getListPageUrl(String str) {
        return str.substring(0, str.lastIndexOf("/") + 1);
    }
}
